-module(ecas_db).
-include_lib("stdlib/include/qlc.hrl").
-compile(export_all).
-export([test/0]).
-record(user, {name,password}).
-record(ticket, {id, user}).

test()->
    hello.

init() ->
    
   case  mnesia:create_schema([node()]) of
     ok->
        mnesia:start(),
        mnesia:create_table(user,   [{attributes, record_info(fields, user)}]),
        mnesia:create_table(ticket,   [{attributes, record_info(fields, ticket)}]),
        reset_tables(),
        mnesia:stop();
     _ ->
	   ok
   end .
    

start() ->
        mnesia:start().
stop() ->
       mnesia:stop().

create_ticket(Id,UserName) ->
    
    Ticket = #ticket{id=Id, user=UserName},
        F = fun() ->
		                    mnesia:write(Ticket)
        end,
        mnesia:transaction(F).
    




%% SQL equivalent
%%  SELECT * FROM shop;

validate(Name,Pass)->
    case do(qlc:q([X || X <- mnesia:table(user),
			X#user.name=:=Name,
			X#user.password=:=Pass])) of
        []->
	    false;
	        _->true
    end .
read_user()->
%%    do(qlc:q([X || X <- nmesia:table(user)])).
      do(qlc:q([X || X <- mnesia:table(user)])).    


read_ticket()->
      do(qlc:q([X || X <- mnesia:table(ticket)])).

reset_tables() ->    
   mnesia:clear_table(user),
  
    mnesia:clear_table(ticket),
    F = fun() ->
                lists:foreach(fun mnesia:write/1, example_tables())
        end,
    mnesia:transaction(F).

 get_ticket(TicketId) ->
        F = fun() ->
		     mnesia:read({ticket, TicketId}) end,
       case  R=mnesia:transaction(F) of
           {_,[]}->
	       false;
	   _ ->{_,[H|_]}=R,
	       H
        end .


do(Q) ->
    F = fun() -> qlc:e(Q) end,
    {atomic, Val} = mnesia:transaction(F),
    Val.



example_tables() ->
    [%% The shop table
     {user, "admin","admin"}
 
    ].


